package org.greenrobot.eventbus.harmony;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import org.greenrobot.eventbus.Logger;

import java.util.logging.Level;

/**
 * 鸿蒙Log
 */
public class HarmonyLogger implements Logger {
    private static final boolean HARMONY_LOG_AVAILABLE;

    static {
        boolean harmony = false;
        try {
            harmony = Class.forName("ohos.hiviewdfx.HiLog") != null;
        } catch (ClassNotFoundException e) {
            // OK
        }
        HARMONY_LOG_AVAILABLE = harmony;
    }

    public static boolean isHarmonyLogAvailable() {
        return HARMONY_LOG_AVAILABLE;
    }


    private final HiLogLabel tag;

    public HarmonyLogger(String tag) {
        if (HARMONY_LOG_AVAILABLE) {
            this.tag = new HiLogLabel(HiLog.DEBUG, 0xAAABB, tag);
        } else {
            this.tag = null;
        }
    }

    public void log(Level level, String msg) {
        if (level != Level.OFF) {
            print(level, msg);
        }
    }

    public void log(Level level, String msg, Throwable th) {
        if (level != Level.OFF) {
            // That's how Log does it internally
            print(level, msg + "\n" + HiLog.getStackTrace(th));
        }
    }

    private void print(Level level, String msg) {
        int value = level.intValue();
        if (value < 800) { // below INFO
            if (value < 500) { // below FINE
                HiLog.debug(tag, msg);
            } else {
                HiLog.debug(tag, msg);
            }
        } else if (value < 900) { // below WARNING
            HiLog.info(tag, msg);
        } else if (value < 1000) { // below ERROR
            HiLog.warn(tag, msg);
        } else {
            HiLog.error(tag, msg);
        }
    }
}